<template>
    <div class="shopping">
        <div v-for="(item, index) in list" :key="index">
            <van-card
                :num="item.num"
                :price="item.price"
                :desc="item.lettor"
                :title="item.shopname"
                thumb="https://img.yzcdn.cn/vant/ipad.jpeg"
            />
            <template>
                <van-button
                    size="mini"
                    @click="add(item.id, item.num, item.price)"
                    >+</van-button
                >
                <span>价格:{{ total }}</span>
                <van-button
                    size="mini"
                    @click="del(item.id, item.num, item.price)"
                    >-</van-button
                >
            </template>
        </div>
    </div>
</template>

<script>
import axios from "axios";
export default {
    data() {
        return {
            list: [],
            price: 0,
            num: 0,
        };
    },
    created() {
        this.ShopAll(); //调用
    },
    methods: {
        //点击+ 数量＋1
        add(id, num, price) {
            this.num = num; //数量
            this.price = price; //价格
            axios.put("/shop/alter", {
                id: id,
                num: num + 1,
            });
            this.ShopAll();
        },
        //点击- 数量-1
        del(id, num, price) {
            this.num = num; //数量
            this.price = price; //价格
            axios.put("/shop/alter", {
                id: id,
                num: num <= 0 ? (num = 0) : num - 1, //三元运算符
            });
            //小于等于0的时候
            if (num <= 0) {
                alert("草拟吗买不买了都tm0了");
            }
            this.ShopAll(); //页面调用
        },
        ShopAll() {
            //列表的数据渲染
            axios.get("/shop/inquire").then((res) => {
                console.log(res.data);
                this.list = res.data.data;
            });
        },
    },
    //计算总价
    computed: {
        total: function() {
            //使用 reduce 方法来让 array 中的所有值相加
            //计算总价
            return this.list.reduce((n, p) => (n += p.num * p.price), 0);
            // console.log(num, prcie);
        },
    },
};
</script>

<style></style>
